//
// Created by LiuYou on 2021/6/22.
//

#include <cstdlib>
#include <cstdio>
#include <pthread.h>
#include <cstring>

static void cleanup_func(void* pVoid) {
    std::puts(static_cast<const char*>(pVoid));
}

static void* func(void* pVoid) {
    std::puts("Thread is working!");

    // TODO 注意: pthread_cleanup_push() 和 pthread_cleanup_pop() 是成对出现的！！！！
    //  有多少个 push 就有多少个 pop。
    pthread_cleanup_push(cleanup_func, (void*) "cleanup:1");
        pthread_cleanup_push(cleanup_func, (void*) "cleanup:2");
            pthread_cleanup_push(cleanup_func, (void*) "cleanup:3");

                std::puts("push over!");

            pthread_cleanup_pop(1);
        pthread_cleanup_pop(0);
    pthread_cleanup_pop(0);

    pthread_exit(nullptr);
}

int main() {
    std::puts("Begin!");
    pthread_t tid{};
    int err = pthread_create(&tid, nullptr, func, nullptr);
    if (err) {
        std::fprintf(stderr, "pthread_create(): %s\n", std::strerror(err));
        std::exit(1);
    }

    pthread_join(tid, nullptr);
    std::puts("End!");

    std::exit(0);
}